const API = require('../../utils/api')
const AUTH = require('../../utils/auth')
Page({
    data: {
        News: [],
    },
    Login() {
        const _this = this;
        wx.getUserProfile({
            //授权语言
            lang: 'zh_CN',
            //授权描述
            desc: '申请用户授权',
            //成功返回
            success(res) {
                console.log('授权成功返回：', res)

                //调用更新用户头像和昵称的方法到
                _this.updateUserInfo(res.userInfo)
                //   const a=  AUTH.autoRegAndLogin()
                //   console.log(a);

            },
            //失败返回
            fail(error) {
                console.log('授权失败返回：', error)
            }
        })
    },
    async updateUserInfo(userInfo) {
        this.setData({
            News: userInfo
        })
        console.log(this.data.News);
        const isLogined = await AUTH.hasUserIsLogined()

        console.log(isLogined);
        if (isLogined) {
            // token
            const token = wx.getStorageSync('token')
            console.log(token);
            const {
                avatarUrl,
                city,
                gender,
                nickName: nick,
                province
            } = userInfo
            await API.updateUserInfoApi({
                city,
                nick,
                province,
                avatarUrl,
                gender,
                token
            })
            this.getUserDetail()
        }
    },
    onShow: async function () {
        const isLogined = await AUTH.hasUserIsLogined()
        if (isLogined) {
            this.getUserDetail()
        }
    },

    async getUserDetail() {
        // 拿到token
        const token = wx.getStorageSync('token')
        const res = await API.getUserDetailApi(token)
        console.log(res.base);
        const data1 = {}
        data1.userinfo = res.base
        if (res.base.avatarUrl && res.base.nick) {
            this.setData({
                isAuth: 2
            })
        } else {
            this.setData({
                isAuth: 1
            })
        }
        this.setData(data1)
    }
})